package my.soft.aiteacher.common.service.Impl;

import cn.hutool.core.codec.Base64;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.code.kaptcha.Producer;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import my.soft.aiteacher.exception.BusinessException;
import my.soft.aiteacher.common.mapStruct.UserMapStruct;
import my.soft.aiteacher.common.mapper.UserMapper;
import my.soft.aiteacher.common.pojo.UserDo;
import my.soft.aiteacher.common.pojo.UserVo;
import my.soft.aiteacher.common.service.IUserService;
import my.soft.aiteacher.utils.JWTUtils;
import my.soft.aiteacher.utils.SimpleRedisLock;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDo> implements IUserService {
    @Resource
    private UserMapper userMapper;
//    @Resource
//    private AuthenticationManager authenticationManager;
    @Resource
    private Producer producer;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private JavaMailSender mailSender;

    @Resource
    private UserMapStruct userMapStruct;

    @Value(value = "${spring.mail.username}")
    private String from;


    @Override
    public String login(UserVo user) {
        if (Objects.isNull(user.getCaptchaId())) {
            throw new BusinessException("验证码id为空");
        }
        if (Objects.isNull(user.getCaptchaCode())) {
            throw new BusinessException("验证码为空");
        }
        if (Boolean.FALSE.equals(redisTemplate.hasKey(user.getCaptchaId()))) {
            throw new BusinessException("验证码已过期");
        }
        if (!Objects.equals(redisTemplate.opsForValue().get(user.getCaptchaId()), user.getCaptchaCode())) {
            throw new BusinessException("验证码错误");
        }
        UserDo loginUser = userMapper.selectOne(new QueryWrapper<UserDo>().eq("username", user.getUsername()));
        String password = user.getPassword();
        PasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if (!bCryptPasswordEncoder.matches(password, loginUser.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }
        return JWTUtils.createToken(userMapStruct.userDoToUserVo(loginUser));

    }

    @Override
    public Map<String, Object> getCaptcha() {
        try {
            Map<String, Object> map = new HashMap<>();
            FastByteArrayOutputStream outputStream = new FastByteArrayOutputStream();
            String code = producer.createText();
            log.info("验证码：{}", code);
            BufferedImage image = producer.createImage(code);
            String uuid = UUID.randomUUID().toString().replace("-", "");
            ImageIO.write(image, "jpg", outputStream);
            redisTemplate.opsForValue().set(uuid, code, 120, TimeUnit.SECONDS);
            map.put("uuid", uuid);
            map.put("captcha", Base64.encode(outputStream.toByteArray()));
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("验证码生成失败,请联系管理员");
        }
    }

    @Override
    public void sendMall(String to) {
        SimpleRedisLock simpleRedisLock = new SimpleRedisLock(redisTemplate, to);
        if (simpleRedisLock.isLocked()) {
            throw new BusinessException("验证码已发送,120秒后再试");
        }
        try {
            //生成四位数验证码
            Random random = new Random();
            int code = random.nextInt(9000) + 1000;
            //发送验证码
            redisTemplate.opsForValue().set(to, String.valueOf(code), 120, TimeUnit.SECONDS);
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom(from);
            mailMessage.setSubject("登录验证码");
            mailMessage.setText("您的验证码是：" + code + "有效期是两分钟，请及时输入");
            mailMessage.setTo(to);
            mailSender.send(mailMessage);

            simpleRedisLock.lock(120L);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("验证码发送失败,请联系管理员");
        }
    }

    @Override
    public String mailLogin(UserVo user) {
        if (Objects.isNull(user.getEmail())) {
            throw new BusinessException("邮箱为空,请联系管理员");
        }
        if (Objects.isNull(user.getEmailCode())) {
            throw new BusinessException("验证码为空");
        }
        if (Boolean.FALSE.equals(redisTemplate.hasKey(user.getEmail()))) {
            throw new BusinessException("验证码已过期");
        }
        if (!Objects.equals(redisTemplate.opsForValue().get(user.getEmail()), user.getEmailCode())) {
            throw new BusinessException("验证码错误");
        }
        UserDo userDo = userMapper.selectOne(new QueryWrapper<UserDo>().eq("email", user.getEmail()));
        if (Objects.isNull(userDo)) {
            throw new BusinessException("邮箱不存在");
        }
        return JWTUtils.createToken(userMapStruct.userDoToUserVo(userDo));
    }

    @Override
    public UserVo getUserDetail(Object principal) {
        UserDo userDo = userMapper.selectOne(new QueryWrapper<UserDo>().eq("username", principal.toString()));
        userDo.setPassword(null);
        UserVo userVo = userMapStruct.userDoToUserVo(userDo);
//        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
//        userVo.setRoles(authorities);
        return userVo;
    }

    @Override
    public void updateUserDetail(UserVo userVo) {
//        userMapper.updateById(userMapStruct.userVoToUserDo(userVo));
    }


}
